package com.chuanshiyidao.huawei;

import android.app.Activity;
import android.content.IntentSender;

import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.iap.Iap;
import com.huawei.hms.iap.IapApiException;
import com.huawei.hms.iap.entity.ConsumeOwnedPurchaseReq;
import com.huawei.hms.iap.entity.ConsumeOwnedPurchaseResult;
import com.huawei.hms.iap.entity.InAppPurchaseData;
import com.huawei.hms.iap.entity.IsEnvReadyResult;
import com.huawei.hms.iap.entity.OrderStatusCode;
import com.huawei.hms.iap.entity.OwnedPurchasesReq;
import com.huawei.hms.iap.entity.OwnedPurchasesResult;
import com.huawei.hms.iap.entity.PurchaseIntentReq;
import com.huawei.hms.iap.entity.PurchaseIntentResult;
import com.huawei.hms.support.api.client.Status;
import com.huawei.hms.support.log.common.Base64;

import org.json.JSONException;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

public class HuaweiPayManager {

    public static String publicKey = "MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAiA9xYjSB7R/j2yPUMVecKb6lLUPBC/8Qo1o/+95FgYT3YjlVFMpfzrqNSPi+7/TSDG8RjCSaHq0DSQGWwytWFsvnEP32TlmvNieWek6/yoqcqTNFT8WzK+uDxbcHB2MDNfbe5+xiXwnHggpagdMOb8zamZSDiyXFb0iscx+NfEUlzT1Y3jA1mAAsmI4DmGSEEdUkTHZskeqmtKdiX2vgH5x24tpVc6HvNwH0c+MnaNmwYaOHqpDL+GrmLuIS7LmrkVIyVYvxpIzfuiPw38D1Gw8yNErUidWdAV4QzcP079jgTgZmIGltcG3rv4opX7KNqB7HS4j4ojMoX0PjWZ/KTtTj/LMX42Sr6FkA0zVL7Z1S2a7R6Z/bEZSukuxCnZAEE2mDFRN6Ja7WLv4cqG7njcM5Zsf0t9QmCuJpFFxzb1b017dmEVTNO08nkzgVS4sgW/vQoPV4kHhLKa72b6hZGRUNPANm2KX20Vsce5256ToNt74DK0IvmwCPvABksclvAgMBAAE=";

    Activity activity = null;
    public HuaweiPayManager(Activity activity){
        this.activity = activity;
    }

    public void canUsedHuaweiPay(){

        Task<IsEnvReadyResult> task = Iap.getIapClient(activity).isEnvReady();
        task.addOnSuccessListener(new OnSuccessListener<IsEnvReadyResult>() {
            @Override
            public void onSuccess(IsEnvReadyResult result) {
                // 获取接口请求的结果
                int accountFlag = result.getAccountFlag();
                int resultCode = result.getReturnCode();
                if(resultCode == OrderStatusCode.ORDER_STATE_SUCCESS){
                    //可以使用华为支付
                }
                Utils.log("accountFlag:" + accountFlag + "  resultCode:" + resultCode);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                if (e instanceof IapApiException) {
                    IapApiException apiException = (IapApiException) e;
                    Status status = apiException.getStatus();
                    if (status.getStatusCode() == OrderStatusCode.ORDER_HWID_NOT_LOGIN) {
                        // 未登录帐号
                        if (status.hasResolution()) {
                            try {
                                // 6666是您自定义的常量
                                // 启动IAP返回的登录页面
                                status.startResolutionForResult(activity, 6666);
                            } catch (IntentSender.SendIntentException exp) {
                                Utils.log("can huawei pay failed2:" + exp.getMessage());
                            }
                        }
                    } else if (status.getStatusCode() == OrderStatusCode.ORDER_ACCOUNT_AREA_NOT_SUPPORTED) {
                        // 用户当前登录的华为帐号所在的服务地不在华为IAP支持结算的国家/地区中
                        Utils.log("当前服务地不在华为支持结算国家/地区");
                    }
                } else {
                    // 其他外部错误
                    Utils.log("can huawei pay failed1:" + e.getMessage());
                }
            }
        });
    }


    public void pay(String produceId){

        // 构造一个PurchaseIntentReq对象
        PurchaseIntentReq req = new PurchaseIntentReq();
        // 通过createPurchaseIntent接口购买的商品必须是您在AppGallery Connect网站配置的商品。
        req.setProductId(produceId);
        // priceType: 0：消耗型商品; 1：非消耗型商品; 2：订阅型商品
        req.setPriceType(0);
        //设置商户侧保留信息。
        req.setDeveloperPayload("test");
        // 调用createPurchaseIntent接口创建托管商品订单
        Task<PurchaseIntentResult> task = Iap.getIapClient(activity).createPurchaseIntent(req);
        task.addOnSuccessListener(new OnSuccessListener<PurchaseIntentResult>() {
            @Override
            public void onSuccess(PurchaseIntentResult result) {
                // 获取创建订单的结果
                Status status = result.getStatus();
                if (status.hasResolution()) {
                    try {
                        // 6666是您自定义的常量
                        // 启动IAP返回的收银台页面
                        status.startResolutionForResult(activity, 7777);
                    } catch (IntentSender.SendIntentException exp) {
                        Utils.log("pay failed1：" + exp.getMessage());
                    }
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                if (e instanceof IapApiException) {
                    IapApiException apiException = (IapApiException) e;
                    Status status = apiException.getStatus();
                    int returnCode = apiException.getStatusCode();
                } else {
                    // 其他外部错误
                }
            }
        });
    }

    /**
     * 校验签名信息
     *
     * @param content 结果字符串
     * @param sign 签名字符串
     * @return 是否校验通过
     */
    public static boolean  doCheck(String content, String sign) {
        if (sign == null) {
            return false;
        }
        if (publicKey == null) {
            return false;
        }
        try {
            // 生成"RSA"的KeyFactory对象
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(publicKey);
            // 生成公钥
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            java.security.Signature signature = null;
            // 根据SHA256WithRSA算法获取签名对象实例
            signature = java.security.Signature.getInstance("SHA256WithRSA");
            // 初始化验证签名的公钥
            signature.initVerify(pubKey);
            // 把原始报文更新到签名对象中
            signature.update(content.getBytes(StandardCharsets.UTF_8));
            // 将sign解码
            byte[] bsign = Base64.decode(sign);
            // 进行验签
            return signature.verify(bsign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 对于消耗型商品 需要确认发货状态
     */
    public void confirmOrder(String inAppPurchaseData){
        // 构造ConsumeOwnedPurchaseReq对象
        ConsumeOwnedPurchaseReq req = new ConsumeOwnedPurchaseReq();
        String purchaseToken = "";
        try {
            // purchaseToken需从购买信息InAppPurchaseData中获取
            InAppPurchaseData inAppPurchaseDataBean = new InAppPurchaseData(inAppPurchaseData);
            purchaseToken = inAppPurchaseDataBean.getPurchaseToken();
        } catch (JSONException e) {
        }
        req.setPurchaseToken(purchaseToken);
        // 消耗型商品发货成功后，需调用consumeOwnedPurchase接口进行消耗
        Task<ConsumeOwnedPurchaseResult> task = Iap.getIapClient(activity)
                .consumeOwnedPurchase(req);
        task.addOnSuccessListener(new OnSuccessListener<ConsumeOwnedPurchaseResult>() {
            @Override
            public void onSuccess(ConsumeOwnedPurchaseResult result) {
                // 获取接口请求结果
                Utils.log("confirm Order success:" + result.getReturnCode());
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                if (e instanceof IapApiException) {
                    IapApiException apiException = (IapApiException) e;
                    Status status = apiException.getStatus();
                    int returnCode = apiException.getStatusCode();
                    Utils.log("confirm Order falied:" + returnCode);
                } else {
                    // 其他外部错误
                }
            }
        });
    }


    /**
     * 检查是否有未完成订单
     *
     * 以下场景触发
     * 应用启动时。
     * 购买请求返回-1（OrderStatusCode. ORDER_STATE_FAILED）时。
     * 购买请求返回60051（OrderStatusCode. ORDER_PRODUCT_OWNED）时
     */
    public void CheckUndoneOrder(){
        // 构造一个OwnedPurchasesReq对象
        OwnedPurchasesReq ownedPurchasesReq = new OwnedPurchasesReq();
        // priceType: 0：消耗型商品; 1：非消耗型商品; 2：订阅型商品
        ownedPurchasesReq.setPriceType(0);
        // 调用obtainOwnedPurchases接口获取所有已购但未发货的消耗型商品的购买信息
        Task<OwnedPurchasesResult> task = Iap.getIapClient(activity).obtainOwnedPurchases(ownedPurchasesReq);
        task.addOnSuccessListener(new OnSuccessListener<OwnedPurchasesResult>() {
            @Override
            public void onSuccess(OwnedPurchasesResult result) {
                // 获取接口请求成功的结果
                if (result != null && result.getInAppPurchaseDataList() != null) {
                    for (int i = 0; i < result.getInAppPurchaseDataList().size(); i++) {
                        String inAppPurchaseData = result.getInAppPurchaseDataList().get(i);
                        String inAppSignature = result.getInAppSignature().get(i);
                        // 使用应用的IAP公钥验证inAppPurchaseData的签名数据
                        // 如果验签成功，确认每个商品的购买状态。确认商品已支付后，检查此前是否已发过货，未发货则进行发货操作。发货成功后执行消耗操作
                        try {
                            InAppPurchaseData inAppPurchaseDataBean = new InAppPurchaseData(inAppPurchaseData);
                            int purchaseState = inAppPurchaseDataBean.getPurchaseState();
                            if(purchaseState == 0){
                                //表示本次交易是成功的 需要补发货

                            }
                        } catch (JSONException e) {
                        }
                    }
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                if (e instanceof IapApiException) {
                    IapApiException apiException = (IapApiException) e;
                    Status status = apiException.getStatus();
                    int returnCode = apiException.getStatusCode();
                } else {
                    // 其他外部错误
                }
            }
        });
    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 6666) {
//            if (data == null) {
//                Log.e("onActivityResult", "data is null");
//                return;
//            }
//            // 调用parsePurchaseResultInfoFromIntent方法解析支付结果数据
//            PurchaseResultInfo purchaseResultInfo = Iap.getIapClient(this).parsePurchaseResultInfoFromIntent(data);
//            switch(purchaseResultInfo.getReturnCode()) {
//                case OrderStatusCode.ORDER_STATE_CANCEL:
//                    // 用户取消
//                    break;
//                case OrderStatusCode.ORDER_STATE_FAILED:
//                case OrderStatusCode.ORDER_PRODUCT_OWNED:
//                    // 检查是否存在未发货商品
//                    break;
//                case OrderStatusCode.ORDER_STATE_SUCCESS:
//                    // 支付成功
//                    String inAppPurchaseData = purchaseResultInfo.getInAppPurchaseData();
//                    String inAppPurchaseDataSignature = purchaseResultInfo.getInAppDataSignature();
//                    // 使用您应用的IAP公钥验证签名
//                    // 若验签成功，则进行发货
//                    // 若用户购买商品为消耗型商品，您需要在发货成功后调用consumeOwnedPurchase接口进行消耗
//                    break;
//                default:
//                    break;
//            }
//        }
//    }
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 6666) {
//            if (data != null) {
//                // 使用parseRespCodeFromIntent方法获取接口请求结果
//                int returnCode = IapClientHelper.parseRespCodeFromIntent(data);
//                // 使用parseAccountFlagFromIntent方法获取接口返回的帐号类型
//                int accountFlag = IapClientHelper.parseAccountFlagFromIntent(data);
//            }
//        }
//    }
}
